package com.apache.uct.service.impl;

import java.util.List;

import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.database.model.Page;
import com.apache.exception.BusinessException;
import com.apache.uct.common.entity.Org;
import com.apache.uct.manager.OrgManager;
import com.apache.uct.util.UctStringUtil;

public class OrgManagerImpl implements OrgManager {

	protected IDao orgDao;
	protected final String entityName = "com.apache.uct.common.entity.Org";

	public void setOrgDao(IDao orgDao) {
		this.orgDao = orgDao;
	}

	public String saveInfo(ParamsVo<Org> vo) throws BusinessException {
		Org org = vo.getObj();
		String infoId = Validator.generate();
		//定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
		//String cacheKey = "";
		String cacheKey = "org_" + infoId;
		org.setOrgId(infoId);
		MethodParam param = new MethodParam("Org", cacheKey, "", entityName);
		param.setVaule(org);
		if (orgDao.insert(param)) {
			updateSubNum(org.getFatherId(), "add");
			return infoId;
		}
		return "";
	}

	public boolean editInfo(ParamsVo<Org> vo) throws BusinessException {
		Org org = vo.getObj();
		if (Validator.isNotNull(org.getOrgId())) {
			//String cacheKey = "";
			String cacheKey = "org_" + org.getOrgId();
			MethodParam param = new MethodParam("Org", cacheKey, "", entityName);
			param.setVaule(org);
			return orgDao.edit(param);
		}
		return false;
	}

	public boolean deleteInfo(ParamsVo<Org> vo) throws BusinessException {
		String infoId = vo.getInfoId();
		if (Validator.isNull(infoId)) {
			return false;
		}
		//String cacheKey = "";
		String cacheKey = "org_" + infoId;
		String mark = Validator.getDefaultStr(String.valueOf(vo.getParams("isDelete")), "true");
		MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
		param.setInfoId(infoId);
		Org info = (Org) orgDao.selectById(param);
		if (Validator.isEmpty(info)) {
			return false;
		}
		param.setVaule(info);//此处需要先将状态值赋值为删除状态
		boolean flag = false;
		if ("false".equals(mark)) {//逻辑删除
			param.setKey("Org");
			flag = orgDao.edit(param);
		} else {
			param.setParams("orgId", infoId);
			param.setDelete(true);
			flag = orgDao.delete(param);
		}
		if (flag) {
			updateSubNum(info.getFatherId(), "del");//更新子节点数
		}
		return flag;
	}

	//修改子节点数
	private void updateSubNum(String orgId, String flag) {
		if (!"0".equals(orgId)) {
			MethodParam param = new MethodParam("ById", "org_" + orgId, "", entityName);
			param.setInfoId(orgId);
			Org org = (Org) orgDao.selectById(param);
			if (Validator.isEmpty(org.getSubCount()))
				org.setSubCount(0);
			int subNum = org.getSubCount();
			if ("add".equals(flag)) {
				org.setSubCount(subNum + 1);
			} else if ("del".equals(flag)) {
				org.setSubCount(subNum - 1);
			}
			param = new MethodParam("Org", "org_" + orgId, "", entityName);
			param.setVaule(org);
			orgDao.edit(param);
		}
	}

	public Object getInfoById(ParamsVo<Org> vo) {
		String infoId = vo.getInfoId();
		//String cacheKey = "";
		String cacheKey = "org_" + infoId;
		if (Validator.isNull(infoId)) {
			return null;
		}
		MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
		param.setInfoId(infoId);
		return orgDao.selectById(param);
	}

	public Object execute(ParamsVo<Org> vo) {
		String key = vo.getKey();
		if ("orgsByUserId".equals(key)) {
			return getOrgsByUserId(vo.getInfoId());
		} else if ("checkOrgEname".equals(key)) {
			Org org = vo.getObj();
			return checkOrgEname(org.getOrgEname());
		} else if ("findOrgByOrgEname".equals(key)) {
			Org org = vo.getObj();
			return findOrgByOrgEname(org.getOrgEname());
		} else if ("ByOrgProperty".equals(key)) {
			return getOrgByProperty(vo);
		}
		return null;
	}

	private Org getOrgByProperty(ParamsVo<Org> vo) {
		String propertyName = String.valueOf(vo.getParams("propertyName"));
		String propertyValue = String.valueOf(vo.getParams("propertyValue"));
		MethodParam param = new MethodParam("ByProperty", "", "", entityName);
		param.setParams(propertyName, propertyValue);
		param.setSqlStr(orgDao.getSql(2) + " and " + propertyName + "=:" + propertyName);
		return (Org) orgDao.selectSingle(param);
	}

	private boolean checkOrgEname(String orgEname) {
		MethodParam param = new MethodParam("ByOrgEname", "", orgDao.getSql(1) + " and orgEname=:orgEname", entityName);
		param.setParams("orgEname", orgEname);
		long count = orgDao.count(param);
		if (count > 0)
			return false;
		return true;
	}

	private Object findOrgByOrgEname(String orgEname) {
		MethodParam param = new MethodParam("ByOrgEname", "", orgDao.getSql(1) + " and orgEname=:orgEname", entityName);
		param.setParams("orgEname", orgEname);
		List list = orgDao.select(param);
		if (!Validator.isEmpty(list))
			return list.get(0);
		return null;
	}

	private List getOrgsByUserId(String userId) {
		MethodParam param = new MethodParam("ByActUserId", "", "", entityName);
		param.setParams("randTime", System.currentTimeMillis() + "");
		param.setParams("userId", userId);
		param.setSqlStr(orgDao.getSql(3));

		return orgDao.select(param);
	}

	public Page getPageInfo(ParamsVo<Org> vo) {
		String orderBy = vo.getKey();
		if (Validator.isNull(orderBy))
			orderBy = "create_time";
		MethodParam param = setMethodParams(vo, 2, orderBy);
		int pageSize = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")), "10"));
		int pageIndex = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")), "1"));
		param.setPageIndex(pageIndex);
		param.setPageSize(pageSize);
		param.setOrderby(orderBy + " desc");
		Page page = orgDao.pageSelect(param);
		return page;
	}

	public List<Org> getList(ParamsVo<Org> vo) {
		String orderBy = vo.getKey();
		if (Validator.isNull(orderBy))
			orderBy = "create_time";
		MethodParam param = setMethodParams(vo, 2, orderBy);
		param.setOrderby(orderBy + " desc");
		return orgDao.select(param);
	}

	public long countInfo(ParamsVo<Org> vo) {
		MethodParam param = setMethodParams(vo, 1, "");
		return orgDao.count(param);
	}

	private MethodParam setMethodParams(ParamsVo<Org> vo, int type, String orderBy) {
		String methodKey = Validator.getDefaultStr(vo.getMethodKey(), "ByProperty");
		StringBuffer sb = new StringBuffer(orgDao.getSql(type));
		MethodParam param = new MethodParam(methodKey, "", "", entityName);
		Org org = vo.getObj();
		if (Validator.isEmpty(org))
			return param;
		if (Validator.isNotNull(org.getSysEname())) {
			sb.append(" and sysEname =:sysEname");
			param.setParams("sysEname", org.getSysEname());
		}
		if (Validator.isNotNull(org.getOrgDomain())) {
			sb.append(" and orgDomain =:orgDomain");
			param.setParams("orgDomain", org.getOrgDomain());
		}
		if (Validator.isNotNull(org.getOrgCname())) {
			sb.append(" and orgCname like '%" + org.getOrgCname() + "%'");
			param.setParams("orgCname", "'%" + org.getOrgCname() + "%'");
		}
		if (Validator.isNotNull(org.getOrgEname())) {
			sb.append(" and orgEname =:orgEname");
			param.setParams("orgEname", org.getOrgEname());
		}
		if (Validator.isNotNull(org.getFullEname())) {
			sb.append(" and fullEname =:fullEname");
			param.setParams("fullEname", org.getFullEname());
		}
		if (Validator.isNotNull(org.getFullCname())) {
			sb.append(" and fullCname =:fullCname");
			param.setParams("fullCname", org.getFullCname());
		}

		if (Validator.isNotNull(org.getOrgCode())) {
			sb.append(" and orgCode =:orgCode");
			param.setParams("orgCode", org.getOrgCode());
		}
		if (Validator.isNotNull(org.getBoss())) {
			sb.append(" and boss =:boss");
			param.setParams("boss", org.getBoss());
		}
		if (Validator.isNotNull(org.getOrgType())) {
			sb.append(" and orgType =:orgType");
			param.setParams("orgType", org.getOrgType());
		}
		if (Validator.isNotNull(org.getOrgRegMoney())) {
			sb.append(" and orgRegMoney =:orgRegMoney");
			param.setParams("orgRegMoney", org.getOrgRegMoney());
		}
		if (Validator.isNotNull(org.getOrgScope())) {
			sb.append(" and orgScope =:orgScope");
			param.setParams("orgScope", org.getOrgScope());
		}
		if (Validator.isNotNull(org.getHomepage())) {
			sb.append(" and homepage =:homepage");
			param.setParams("homepage", org.getHomepage());
		}
		if (Validator.isNotNull(org.getLinkMan())) {
			sb.append(" and linkMan =:linkMan");
			param.setParams("linkMan", org.getLinkMan());
		}
		if (Validator.isNotNull(org.getPhone())) {
			sb.append(" and phone =:phone");
			param.setParams("phone", org.getPhone());
		}
		if (Validator.isNotNull(org.getFax())) {
			sb.append(" and fax =:fax");
			param.setParams("fax", org.getFax());
		}
		if (Validator.isNotNull(org.getMobile())) {
			sb.append(" and mobile =:mobile");
			param.setParams("mobile", org.getMobile());
		}
		if (Validator.isNotNull(org.getEmail())) {
			sb.append(" and email =:email");
			param.setParams("email", org.getEmail());
		}
		if (Validator.isNotNull(org.getProvince())) {
			sb.append(" and province =:province");
			param.setParams("province", org.getProvince());
		}
		if (Validator.isNotNull(org.getCity())) {
			sb.append(" and city =:city");
			param.setParams("city", org.getCity());
		}
		if (Validator.isNotNull(org.getAddress())) {
			sb.append(" and address =:address");
			param.setParams("address", org.getAddress());
		}
		if (Validator.isNotNull(org.getPostCode())) {
			sb.append(" and postCode =:postCode");
			param.setParams("postCode", org.getPostCode());
		}
		if (Validator.isNotNull(org.getOrgRemark())) {
			sb.append(" and orgRemark =:orgRemark");
			param.setParams("orgRemark", org.getOrgRemark());
		}
		if (Validator.isNotNull(org.getUpdateUser())) {
			sb.append(" and updateUser =:updateUser");
			param.setParams("updateUser", org.getUpdateUser());
		}
		if (Validator.isNotNull(org.getCreateUser())) {
			sb.append(" and createUser =:createUser");
			param.setParams("createUser", org.getCreateUser());
		}
		String isSysUser = String.valueOf(vo.getParams("sysUser"));
		if (Validator.isNotNull(isSysUser) && !"1".equals(isSysUser)) {//非系统用户
			String userOrgId = String.valueOf(vo.getParams("userOrgId"));
			String orgIds = String.valueOf(vo.getParams("orgIds"));
			if ("1".equals(SystemTools.getInstance().getValue("manager_suborg"))) {//可以管理子机构
				if (Validator.isNotNull(org.getFatherId()) && "0".equals(org.getFatherId())) {
					if ("2".equals(isSysUser)) {
						param.setParams("orgIds", orgIds);
					} else {
						sb.append(" and orgId =:orgId");
						param.setParams("orgId", userOrgId);
					}
				} else if (Validator.isNotNull(org.getFatherId())) {
					sb.append(" and fatherId =:fatherId");
					param.setParams("fatherId", org.getFatherId());
				}
			} else {
				sb.append(" and orgId =:orgId");
				param.setParams("orgId", userOrgId);
			}
		} else {//系统用户操作
			if (Validator.isNotNull(org.getFatherId())) {
				sb.append(" and fatherId =:fatherId");
				param.setParams("fatherId", org.getFatherId());
			}
		}

		if (Validator.isNotNull(orderBy)) {
			sb.append(" order by " + UctStringUtil.toCamelNamed(orderBy) + " desc");
		}
		param.setSqlStr(sb.toString());
		return param;
	}
}
